import update from "react-addons-update";

/**
 * list 模板
 * {
 *     key:必传，抽屉唯一id
 *     component:必传，抽屉显示组件
 *     modalProps:可空，抽屉api参数，参考https://ant.design/components/drawer-cn/
 *     comProps:可空，传递到子组件参数
 * }
 */
const DrawerReducer: object = {
    namespace: "drawerReducer",
    state: {
        list: []
    },
    updateDrawer: function (params: any) {
        // @ts-ignore
        const {data = {}}: { data: any } = params,
            {list = []}: { tabs: any[] } = this.state;
        let curIndex: number = list.findIndex((item: any) => item?.key === data.key);

        let node: any = curIndex !== -1 ? list[curIndex] : data;

        //连续打开弹框时修改其隐藏状态
        node.open = !node.open;

        let newList: object[] = curIndex !== -1 ? update(list, {$splice: [[curIndex, 1, node]]}) : update(list, {$push: [data]});

        //同时只能弹出一个抽屉
        if (node.open) {
            newList.forEach((item: any) => {
                item.open = item.key === node.key ? node.open : false
            })
        }

        // @ts-ignore
        return update(this.state, {list: {$set: newList}})
    },
    openDrawer: function (params: any) {
        // @ts-ignore
        const {key}: { key: string } = params,
            {list}: { tabs: object[] } = this.state;
        let curNode = list.find((item: any) => item?.key === key);
        // @ts-ignore
        return this.updateDrawer({data: curNode});
    },

    createDrawer: function (params: any) {
        const {data = {}}: { data: any } = params;
        // @ts-ignore
        return this.updateDrawer({data})
    },
    removeDrawer: function (key: string) {
        // @ts-ignore
        const {list}: { list: object[] } = this.state;

        let curIndex: number = list.findIndex((item: any) => item.key === key);
        let newList: object[] = update(list, {$splice: [[curIndex, 1]]});

        // @ts-ignore
        return update(this.state, {list: {$set: newList}})
    },
    removeAll: function () {
        // @ts-ignore
        return {
            ...this.state,
            list: []
        }
    }
};

export default DrawerReducer;